﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WebApplication9
{
    public interface IGoogleSTTService
    {
        Task<string> SpeechToTextAsync(AudioEncoding encoding, string language, string speech);
    }

    public class GoogleSTTService : HttpSendService, IGoogleSTTService
    {
        private bool Debug { get; } = false;
        public GoogleSTTService()
        {
#if DEBUG
            //Debug = true;
#endif
        }

        public async Task<string> SpeechToTextAsync(AudioEncoding encoding, string language, string speech)
        {            
            if (Debug)
            {
                return JsonConvert.SerializeObject(new
                {
                    text = "Hello world from sppech!",
                    score = 9.5,
                });
            }
            else
            {
                string url = $"https://content-speech.googleapis.com/v1/speech:recognize?alt=json";
                int? sampleRateHertz = null;
                if (encoding != AudioEncoding.LINEAR16)
                {//8000, 12000, 16000, 24000, 48000
                    sampleRateHertz = 16000;
                }

                var json = JsonConvert.SerializeObject(new RecognizeRequest
                {
                    audio = new RecognitionAudio
                    {
                        content = speech,
                    },
                    config = new RecognitionConfig
                    {
                        encoding = encoding,
                        languageCode = language,
                        enableAutomaticPunctuation = true,
                        sampleRateHertz = sampleRateHertz,
                    }
                });
                HttpRequestMessage httpRequestMessage = new HttpRequestMessage
                {
                    Content = new StringContent(json, Encoding.UTF8, "application/json"),
                };
                HttpResponseMessage httpResponseMessage = await PostAsync(httpRequestMessage, url, 60);
                string strResult = await httpResponseMessage.Content.ReadAsStringAsync();
                if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    RecognizeResponse recognizeResponse = JsonConvert.DeserializeObject<RecognizeResponse>(strResult);
                    string text = "";
                    decimal score = 0;
                    foreach (var result in recognizeResponse.results)
                    {
                        text += string.Join(" ", result.alternatives?.Select(a => a.transcript));
                        var alternative = result.alternatives?.FirstOrDefault();
                        if (alternative != null)
                        {
                            score = alternative.confidence;
                        }
                    }

                    return JsonConvert.SerializeObject(new
                    {
                        text = text,
                        score = score,
                    });
                }
                else
                {
                    RecognizeResponse recognizeResponse = JsonConvert.DeserializeObject<RecognizeResponse>(strResult);
                    throw new Exception(recognizeResponse?.error?.message);
                }

                //string url = $"https://content-speech.googleapis.com/v1/speech:recognize?alt=json&key={GoogleApiKey}";
                //using(HttpClient httpClient = new HttpClient())
                //{
                //    int? sampleRateHertz = null;
                //    if(encoding != AudioEncoding.LINEAR16)
                //    {
                //        sampleRateHertz = 24000;
                //    }

                //    var json = JsonConvert.SerializeObject(new RecognizeRequest
                //    {
                //        audio = new RecognitionAudio
                //        {
                //            content = speech,
                //        },
                //        config = new RecognitionConfig
                //        {
                //            encoding = encoding,
                //            languageCode = language,
                //            enableAutomaticPunctuation = true,
                //            sampleRateHertz = sampleRateHertz,
                //        }
                //    });
                //    StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
                //    HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(url, content);
                //    string strResult = await httpResponseMessage.Content.ReadAsStringAsync();
                //    if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                //    {
                //        RecognizeResponse recognizeResponse = JsonConvert.DeserializeObject<RecognizeResponse>(strResult);
                //        string text = "";
                //        decimal score = 0;
                //        foreach (var result in recognizeResponse.results)
                //        {
                //            text += string.Join(" ",result.alternatives?.Select(a => a.transcript));
                //            var alternative = result.alternatives?.FirstOrDefault();
                //            if (alternative != null)
                //            {
                //                score = alternative.confidence;
                //            }                            
                //        }

                //        return JsonConvert.SerializeObject(new
                //        {
                //            text = text,
                //            score = score,
                //        });
                //    }
                //    else
                //    {
                //        RecognizeResponse recognizeResponse = JsonConvert.DeserializeObject<RecognizeResponse>(strResult);
                //        throw new Exception(recognizeResponse?.error?.message);
                //    }
                //}

            }

        }
    }
}
